package org.ysling.litemall.wx.service;
// Copyright (c) [ysling] [927069313@qq.com]
// [litemall-plus] is licensed under Mulan PSL v2.
// You can use this software according to the terms and conditions of the Mulan PSL v2.
// You may obtain a copy of Mulan PSL v2 at:
//             http://license.coscl.org.cn/MulanPSL2
// THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
// EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
// MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
// See the Mulan PSL v2 for more details.
import com.github.pagehelper.Page;
import com.github.pagehelper.PageInfo;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.ysling.litemall.core.utils.ResponseUtil;
import org.ysling.litemall.db.constant.GrouponConstant;
import org.ysling.litemall.db.vomain.GrouponRuleVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.ysling.litemall.db.domain.LitemallGoods;
import org.ysling.litemall.db.domain.LitemallGroupon;
import org.ysling.litemall.db.domain.LitemallGrouponRules;
import org.ysling.litemall.db.service.LitemallGoodsService;
import org.ysling.litemall.db.service.LitemallGrouponRulesService;
import org.ysling.litemall.db.service.LitemallGrouponService;

import java.util.List;

import static org.ysling.litemall.wx.util.WxResponseCode.*;
import static org.ysling.litemall.wx.util.WxResponseCode.GROUPON_JOIN;

@Service
public class WxGrouponRuleService {
    private final Log logger = LogFactory.getLog(WxGrouponRuleService.class);

    @Autowired
    private LitemallGrouponRulesService grouponRulesService;
    @Autowired
    private LitemallGoodsService goodsService;
    @Autowired
    private LitemallGrouponService grouponService;

    public List<GrouponRuleVo> queryList(Integer page, Integer size, String sort, String order) {
        List<LitemallGrouponRules> grouponRules = grouponRulesService.queryList(page, size, sort, order);
        PageInfo<LitemallGrouponRules> grouponRulesList = PageInfo.of(grouponRules);

        Page<GrouponRuleVo> grouponList = new Page<GrouponRuleVo>();
        grouponList.setPages(grouponRulesList.getPages());
        grouponList.setPageNum(grouponRulesList.getPageNum());
        grouponList.setPageSize(grouponRulesList.getPageSize());
        grouponList.setTotal(grouponRulesList.getTotal());

        for (LitemallGrouponRules rule : grouponRulesList.getList()) {
            Integer goodsId = rule.getGoodsId();
            LitemallGoods goods = goodsService.findById(goodsId);
            if (goods == null || !goods.getIsOnSale()) continue;

            GrouponRuleVo grouponRuleVo = new GrouponRuleVo();
            grouponRuleVo.setId(goods.getId());
            grouponRuleVo.setName(goods.getName());
            grouponRuleVo.setBrief(goods.getBrief());
            grouponRuleVo.setPicUrl(goods.getPicUrl());
            grouponRuleVo.setCounterPrice(goods.getCounterPrice());
            grouponRuleVo.setRetailPrice(goods.getRetailPrice());
            grouponRuleVo.setGrouponPrice(goods.getRetailPrice().subtract(rule.getDiscount()));
            grouponRuleVo.setGrouponDiscount(rule.getDiscount());
            grouponRuleVo.setGrouponMember(rule.getDiscountMember());
            grouponRuleVo.setExpireTime(rule.getExpireTime());
            grouponList.add(grouponRuleVo);
        }

        return grouponList;
    }

    /**
     * 验证团购是否有效
     * @return
     */
    public Object isGroupon(Integer grouponId){
        LitemallGroupon groupon = grouponService.queryById(grouponId);
        if (groupon == null) return ResponseUtil.badArgument();
        //验证活动是否有效
        LitemallGrouponRules rules = grouponRulesService.findById(groupon.getRulesId());
        if (rules == null) return ResponseUtil.badArgument();

        //团购规则已经过期
        if (rules.getStatus().equals(GrouponConstant.RULE_STATUS_DOWN_EXPIRE)) {
            return ResponseUtil.fail(GROUPON_EXPIRED, "团购已过期!");
        }
        //团购规则已经下线
        if (rules.getStatus().equals(GrouponConstant.RULE_STATUS_DOWN_ADMIN)) {
            return ResponseUtil.fail(GROUPON_OFFLINE, "团购已下线!");
        }
        //团购人数已满
        if(grouponService.countGroupon(grouponId) >= (rules.getDiscountMember() - 1)){
            return ResponseUtil.fail(GROUPON_FULL, "团购活动人数已满!");
        }
        return null;
    }

    /**
     * 验证团购是否有效
     * @param grouponRulesId
     * @param grouponLinkId
     * @param userId
     * @return
     */
    public Object isGroupon(Integer grouponRulesId , Integer grouponLinkId , Integer userId){
        //如果是团购项目,验证活动是否有效
        LitemallGrouponRules rules = grouponRulesService.findById(grouponRulesId);
        //找不到记录
        if (rules == null) return ResponseUtil.badArgument();
        //团购规则已经过期
        if (rules.getStatus().equals(GrouponConstant.RULE_STATUS_DOWN_EXPIRE)) {
            return ResponseUtil.fail(GROUPON_EXPIRED, "团购已过期!");
        }
        //团购规则已经下线
        if (rules.getStatus().equals(GrouponConstant.RULE_STATUS_DOWN_ADMIN)) {
            return ResponseUtil.fail(GROUPON_OFFLINE, "团购已下线!");
        }

        if (grouponLinkId != null && grouponLinkId > 0) {
            //团购人数已满
            if(grouponService.countGroupon(grouponLinkId) >= (rules.getDiscountMember() - 1)){
                return ResponseUtil.fail(GROUPON_FULL, "团购活动人数已满!");
            }
            // TODO 这里业务方面允许用户多次开团，以及多次参团，
            // 但是会限制以下两点：
            // （1）不允许参加已经加入的团购
            if(grouponService.hasJoin(userId, grouponLinkId)){
                return ResponseUtil.fail(GROUPON_JOIN, "团购活动已经参加!");
            }
            // （2）不允许参加自己开团的团购
            LitemallGroupon groupon = grouponService.queryById(userId, grouponLinkId);
            if(groupon!=null) {
                if(groupon.getCreatorUserId().equals(userId)){
                    return ResponseUtil.fail(GROUPON_JOIN, "团购活动已经参加!");
                }
            }
        }
        return null;
    }


    /**
     * 添加团购信息
     * @param orderId
     * @param userId
     * @param grouponRulesId
     * @param grouponLinkId
     * @return
     */
    public Integer addGroupon(Integer orderId, Integer userId, Integer grouponRulesId , Integer grouponLinkId){
        LitemallGroupon groupon = new LitemallGroupon();
        groupon.setOrderId(orderId);
        groupon.setStatus(GrouponConstant.STATUS_NONE);
        groupon.setUserId(userId);
        groupon.setRulesId(grouponRulesId);

        //参与者
        if (grouponLinkId != null && grouponLinkId > 0) {
            //参与的团购记录
            LitemallGroupon baseGroupon = grouponService.queryById(grouponLinkId);
            groupon.setCreatorUserId(baseGroupon.getCreatorUserId());
            groupon.setGrouponId(grouponLinkId);
            groupon.setShareUrl(baseGroupon.getShareUrl());
            grouponService.createGroupon(groupon);
        } else {
            groupon.setCreatorUserId(userId);
            groupon.setGrouponId(0);
            grouponService.createGroupon(groupon);
            grouponLinkId = groupon.getId();

            return grouponLinkId;
        }

        return null;
    }

}